package cn.com.fuhuitong.main.home.ui.activity

import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.webkit.WebView
import android.widget.TextView
import androidx.lifecycle.Observer
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.entity.EmptyState
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.home.adapter.MVT
import cn.com.fuhuitong.main.home.adapter.MemberContentAdapter
import cn.com.fuhuitong.main.home.adapter.MemberListAdapter
import cn.com.fuhuitong.main.home.vm.MemberViewModel
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import cn.com.fuhuitong.R
import kotlinx.android.synthetic.main.activity_home_member.*

@Route(path = ARouteConstance.ACTIVITY_URL_MEMBER)
class HomeMemberActivity : ViewModeActivity<MemberViewModel>() {

    @Autowired(name = AppConstance.BUNDLE_MEMBER_ACTION)
    @JvmField
    var memberAction: Int = 0

    private var goodsId: Int = 0
    private var isMemberListClick = false

    private lateinit var memberListAdapter: MemberListAdapter
    private lateinit var memberContentAdapter: MemberContentAdapter

    override fun viewModel(): MemberViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_home_member

    override fun initView() {

        image_member_back.setOnClickListener {
            this.finish()
        }

        with(text_member_title) {
            text = when (memberAction) {
                1 -> "健康大使"
                2 -> "家庭驿站"
                3 -> "实体店"
                else -> "会员权益"
            }
        }

        this.initViewRecyclerAdapter(
            recycler_benefit_list, arrayOf(MVT.MEMBER_LIST.ordinal)
        )

//        var scrollY = 0
//        recycler_benefit_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
//            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                super.onScrolled(recyclerView, dx, dy)
//                scrollY += dy
//            }
//        })

        val adapters: MutableList<DelegateAdapter.Adapter<*>> = mutableListOf(
            MemberListAdapter(
                applicationContext, LinearLayoutHelper().apply {
                    paddingTop = resources.getDimensionPixelSize(R.dimen.dp_30)
                }
            ).apply {
                memberListAdapter = this
            }
        )
        if (memberAction != 0) {
            adapters.add(adapters.size, MemberContentAdapter(
                applicationContext, LinearLayoutHelper().apply {
                    marginTop = resources.getDimensionPixelSize(R.dimen.dp_10)
                }
            ).apply {
                memberContentAdapter = this
            })
        }
        delegateAdapter.addAdapters(adapters)

        memberListAdapter.setOnItemChildClickListener { view, i, memberEntity ->
            if (view.id == R.id.linear_member_open) {
                goodsId = memberEntity.goods_id
                isMemberListClick = true
                viewModel.configValue(arrayOf("contract"))
            }
        }
    }

    override fun initViewMode() {
        viewModel.memberDataLiveData.observe(this, Observer { response ->
            handlerResponseEmpty(
                status = response.status, message = response.statusTip,
                length = response.response?.data?.size ?: 0
            )
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                if (it.size == 0)
                    return@let
                memberListAdapter.setAddDataNew(it)
                when (memberAction) {
                    1 -> viewModel.configValue(arrayOf("health_ambassador_text"))
                    2 -> viewModel.configValue(arrayOf("description_family_station"))
                    3 -> viewModel.configValue(arrayOf("flagship_store"))
                }
            }
        })
        viewModel.configDataLiveData.observe(this, Observer { response ->
            if (isMemberListClick) {
                handlerResponseLoading(response.status, response.statusTip)
            }
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {

                if (isMemberListClick && it.contract.isNotEmpty()) {
                    isMemberListClick = false
                    layDialog(it.contract, goodsId)
                } else {
                    memberContentAdapter.setAddDataNew(
                        mutableListOf(
                            when (memberAction) {
                                1 -> it.health_ambassador_text ?: ""
                                2 -> it.description_family_station ?: ""
                                3 -> it.flagship_store ?: ""
                                else -> "<p>sadasfdgd<\\/p>"
                            }
                        )
                    )
                }
            }
        })
    }

    override fun initData() {
        when (memberAction) {
            1 -> viewModel.memberItem(1)
            2 -> viewModel.memberItem(2)
            3 -> viewModel.memberItem(3)
            else -> viewModel.memberList()
        }
    }

    override fun onLoadingEmptyView(state: EmptyState) {
        super.onLoadingEmptyView(state)
        initData()
    }


    /**
     * 自定义布局的对话框
     */
    private fun layDialog(content: String, goodsId: Int) {
        val view: View = LayoutInflater.from(this).inflate(
            R.layout.dialog_contract, null, false
        )
        val dialog = Dialog(this)
        dialog.setContentView(view)
        dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
        val contentWebView: WebView = view.findViewById(R.id.web_dialog_contract_content)
        contentWebView.loadDataWithBaseURL(
            null, content, "text/html", "UTF-8", null
        )
        view.findViewById<TextView>(R.id.text_dialog_contract_agree)
            .setOnClickListener {
                dialog.cancel()
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_GOODS_DETAILS)
                    .withInt(AppConstance.BUNDLE_GOODS_ID, goodsId)
                    .withBoolean(AppConstance.BUNDLE_GOODS_MEMBER, true)
                    .navigation()
            }
        dialog.show()
    }


    //获取屏幕高度
    fun getScreenWidth(context: Context): Int {
        return context.resources?.displayMetrics?.widthPixels ?: 0
    }

    //获取屏幕高度
    fun getScreenHeight(context: Context): Int {
        return context.resources?.displayMetrics?.heightPixels ?: 0
    }
}